﻿using MediatR;
using SY.BasicData.Api.Write.Basic.Applications.Command;
using SY.BasicData.Domain.Basic;
using SY.BasicData.ErrorCode;
using SY.BasicData.Infrastructures;

namespace SY.BasicData.Api.Write.Basic.Applications.CommandHandler
{
    public class DelRangBaseCommandHandler : IRequestHandler<DelRangBaseCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<BasicModel> basicRepository;

        public DelRangBaseCommandHandler(IBaseRepository<BasicModel> basicRepository)
        {
            this.basicRepository = basicRepository;
        }

        public async Task<ApiResult<int>> Handle(DelRangBaseCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            result.Code = ApiEnum.Success;
            result.Message = "基本信息批量删除成功";
            var Deletes = basicRepository.GetAll().Where(x => request.ids.Contains(x.Id)).ToList();
            if (Deletes == null)
            {
                result.Message = "找不到编号";
                result.Code = ApiEnum.Fail;
                return await Task.FromResult(result);

            }
            foreach (var Delete in Deletes)
            {
                Delete.IsDeleted = true;

            }
            var res = await basicRepository.UpdateRange(Deletes);
            result.Data = res;
            result.Code = res > 0 ? ApiEnum.Success : ApiEnum.Fail;
            result.Message = res > 0 ? "批量删除成功" : "批量删除失败";
            return await Task.FromResult(result);
        }
    }
}
